Page({
	data: {
		//用户全局信息
    userInfo: null,
    checkDish:[],
    globalData: { 
      totalPrice: 0, 
      totalSelected: 0 },
    dish: [],
		number: 1
  },
  redirectTo: function(event) {
    // 获取自定义数据
    const url = event.currentTarget.dataset.url;
    // 使用 wx.redirectTo 进行页面跳转
    wx.redirectTo({
      url: url
    });
  },
	computed() {},
	onLoad(option) {
    this.setData({
      userInfo: app.globalData.userInfo
    })
    this.init();
	},
	async init() {
    let openId = this.data.userInfo._openid;
    this.getShopByUserId(openId);
  },
  async getShopByUserId(id) {
    console.log(id);
    try {
      const res = await wx.cloud.callFunction({
        name: 'getShopByUserId',
        data: {
          openId: id
        }
      });
      if (res.result.code === 0) {
        this.setData({
          dish: res.result.data.data
        });
        console.log(this.data.dish); // 打印更新后的食物列表数据
      } else {
        console.error('获取食物失败:', res.result.msg);
      }
    } catch (err) {
      console.error('调用云函数时发生错误:', err);
    }
  },
	// totalPrice 自定义方法
	async totalPriceFunction(param) {
		let total = 0;
    let checked = 1;
    let myCheckDish = [];
		this.data.dish.forEach((item) => {
			if (item.selected == 1) {
        myCheckDish.push(item._id);
        total = total + item.foodPrice * 0.01 * item.number;
			} else {
				checked = 0;
			}
    });
    this.setData({
      checkDish : myCheckDish
    })
    let myGlobal={
      totalPrice:Number(total.toFixed(2)),
      totalSelected:checked
    }
    this.setData({
      globalData:myGlobal
    })
	},
	// selectAll 自定义方法
	async selectAllFunction(param) {
		this.data.globalData.totalSelected = this.data.globalData.totalSelected === 1 ? 0 : 1;
		//设置选中或取消
    let myDish = this.data.dish
    myDish.forEach((item) => {
			item.selected = this.data.globalData.totalSelected;
    });
    this.setData({
      dish:myDish
    })
		//计算总价
		this.totalPriceFunction();
	},
	// selectOne 自定义方法
	async selectOneFunction(param) {
    console.log(param);
		let index = param && param.index ? param.index : param.index || this.data.index;
    let myDish = this.data.dish
    //选中或者取消
    myDish[param.index].selected = myDish[param.index].selected == '1' ? '0' : '1';
    this.setData({
      dish:myDish
    })
    console.log(this.data.dish[param.index].selected);
		//计算总价
		this.totalPriceFunction();
	},
	changeNumber(evt) {
    const index = evt.currentTarget.dataset.index;
  // 获取新的数值
  const number = evt.detail;
  console.log(number);
  // 更新对应菜品的数量
  const dish = this.data.dish;
  dish[index].number = number;
  // 更新页面数据
  this.setData({
    dish: dish
  });
  console.log(this.data.dish);

  this.updateShop(dish[index]._id,number);

  // 重新计算总价
  this.totalPriceFunction();
  },
  async updateShop(id,number){
    console.log(id);
    console.log(number);
    try {
      const res = await wx.cloud.callFunction({
        name: 'updateShop',
        data: {
          id:id,
          number:Number(number) 
        }
      });
      if (res.result.status === 0) {
        console.log(this.data.dish); // 打印更新后的食物列表数据
      } else {
        console.error('更新失败:', res.result.msg);
      }
    } catch (err) {
      console.error('调用云函数时发生错误:', err);
    }
  },
  async delFood(event) {
    // 获取要删除的地址ID，假设每个地址都有一个唯一的ID
    const foodid = event.currentTarget.dataset.id._id;
    console.log("PPP")
    console.log(foodid)
    // 显示模态对话框询问用户是否确定删除
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (modalSuccess) => {
        if (modalSuccess.confirm) {
          // 用户点击确定，调用云函数删除地址
          wx.cloud.callFunction({
            name: 'delFood',
            data: {
              id: foodid // 假设您是通过ID来删除特定的地址
            },
            success: (res) => {
              console.log(res.result.code)
              if (res.result.code === 0) {
                // 删除成功，从页面数据中移除该地址
                wx.showToast({
                  title: '删除成功',
                });
                this.getShopByUserId(this.data.userInfo._openid);
              } else {
                // 删除失败，提示用户
                wx.showToast({
                  title: res.result.msg || '删除失败',
                  icon: 'none',
                });
              }
            },
            fail: (err) => {
              // 调用云函数失败，提示用户
              wx.showToast({
                title: '删除操作失败',
                icon: 'none',
              });
              console.error('调用云函数时发生错误:', err);
            }
          });
        }
        if (modalSuccess.cancel) {
          console.log("不删除");
        }
      }
    });
  },
  checkToBuy(){
    const checkDishJson = JSON.stringify(this.data.checkDish);
    wx.navigateTo({
      url: `/pages/checkToBuy/checkToBuy?checkDish=${encodeURIComponent(checkDishJson)}`
    });
  }
});
const app=getApp()